package com.jappydb;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import freemarker.template.SimpleNumber;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class JUtils {
	public static TemplateModel wrap(Object o) {
		if (o == null)
			return null;
		if (o.equals(null))
			return null;
		if (o instanceof JObject)
			return (JObject) o;
		if (o instanceof JArray) 
			return (JArray) o;
		if (o instanceof Number)
			return new SimpleNumber((Number) o);
		if (o instanceof String) 
			return new SimpleScalar((String) o);
		if (o instanceof Boolean) {
			final boolean value = ((Boolean)o).booleanValue(); 
			return new TemplateBooleanModel() {
				public boolean getAsBoolean() throws TemplateModelException {
					return value;
				}
			};
		}
		throw new IllegalArgumentException("Can't wrap " + o.getClass());
	}
	
	/**
	 * Static Functions.
	 */
	
	static String appendKeys(String parent, String kid) {
		if (parent == null)
			return kid;
		if (parent.length() == 0)
			return kid;
		return parent + "." + kid;
	}

	static String getParentKey(String key) {
		int i = key.lastIndexOf('.');
		if (i == -1)
			return null;
		return key.substring(0, i);
	}
	
	static String getShortKey(String key) {
		if (key == null)
			return "";
		int dot = key.lastIndexOf('.');
		if (dot == -1)
			return key;
		return key.substring(dot + 1);
	}
	
	/**
	 * Transforms the string to one of JObject, JArray or String.
	 * 
	 * @param context
	 * @param value
	 * @return
	 */
	public static Object stringToJ(JContext context, String value) {
		try {
			JSONArray a = new JSONArray(value);
			return new JArray(context, a);
		} catch (JSONException e) {
			
		}
		try {
			JSONObject o = new JSONObject(value);
			return new JObject(context, o);
		} catch (JSONException e) {
			
		}
		return value;
	}
	
	public static Object objectToJ(JContext context, Object value) throws JSONException {
		if (value instanceof JSONObject) {
			return new JObject(context, (JSONObject) value);
		} else if (value instanceof JSONArray) {
			return new JArray(context, (JSONArray) value);
		} else {
			return value.toString();
		}
	}
}
